error
A Sumor Cloud Tool.
More Documentation
A error handling library support multi-language, predefine error code and passing data.
Installation
npm i @sumor/error --save
Prerequisites
Node.JS version
Require Node.JS version 18.x or above
require Node.JS ES module
As this package is written in ES module,
please change the following code in your package.json
file:
{
"type": "module"
}
Usage
Define Error
import defineError from '@sumor/error'
const MyError = defineError({
code: {
USER_NOT_FOUND: 'User not found',
USER_EXISTED: 'User {name} existed'
}
})
throw new MyError('USER_NOT_FOUND')
throw new MyError('USER_EXISTED', { name: 'Alice' })
Multi-language
import defineError from '@sumor/error'
const MyError = defineError({
language: 'en',
code: {
USER_NOT_FOUND: 'User not found',
USER_EXISTED: 'User {name} existed'
},
i18n: {
zh: {
USER_NOT_FOUND: '用户未找到',
USER_EXISTED: '用户 {name} 已存在'
}
}
})
const error = new MyError('USER_EXISTED', { name: 'Alice' })
error.language = 'en'
console.log(error)
error.language = 'zh'
console.log(error)
Convert Error to JSON
import defineError from '@sumor/error'
const MyError = defineError({
code: {
USER_NOT_FOUND: 'User not found',
USER_EXISTED: 'User {name} existed'
}
})
const error = new MyError('USER_EXISTED', { name: 'Alice' })
console.log(error.json())
Underlying Error
import defineError from '@sumor/error'
const MyError = defineError({
code: {
FIELD_VERIFY_FAILED: 'Field verify failed',
FIELD_CANNOT_EMPTY: 'Field {name} cannot be empty',
FIELD_TOO_LONG: 'Field {name} is too long'
},
i18n: {
zh: {
FIELD_VERIFY_FAILED: '字段验证失败',
FIELD_CANNOT_EMPTY: '字段 {name} 不能为空',
FIELD_TOO_LONG: '字段 {name} 过长'
}
}
})
const error = new MyError('FIELD_VERIFY_FAILED', {}, [
new MyError('FIELD_CANNOT_EMPTY', { name: 'username' }),
new MyError('FIELD_TOO_LONG', { name: 'password' })
])
console.log(error.json())
error.language = 'zh'
console.log(error.json())
Combine Standard Error
import defineError from '@sumor/error'
const MyError = defineError({
code: {
FIELD_VERIFY_FAILED: 'Field verify failed',
FIELD_CANNOT_EMPTY: 'Field {name} cannot be empty',
FIELD_TOO_LONG: 'Field {name} is too long'
}
})
const error = new MyError('FIELD_VERIFY_FAILED', {}, [
new MyError('FIELD_CANNOT_EMPTY', { name: 'username' }),
new MyError('FIELD_TOO_LONG', { name: 'password' }),
new Error('Unknown Error')
])
console.log(error.json())